package com.medical.gateway.config;


import cn.dev33.satoken.httpauth.basic.SaHttpBasicUtil;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 客户端配置
 */
@Configuration
@Slf4j
public class SecurityConfig {

    /**
     * 注册 Sa-Token全局过滤器 （网关）
     */
    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                .addInclude("/**")   /* 拦截全部path */
                .addExclude("/**/doc.*",
                        "/**/swagger-ui.*",
                        "/**/swagger-resources",
                        "/**/webjars/**",
                        "/**/v3/api-docs/**")
                .addExclude("/favicon.ico", "/actuator", "/actuator/**")
                //鉴权方法：每次访问进入
                .setAuth(obj -> {
                    //登录校验 -- 拦截所有路由，并排除/service-auth下的接口 用于开放认证登录
                    SaRouter.match("/**", "/service-auth/api/v1/auth/**", r -> StpUtil.checkLogin());
                    // 权限认证 -- 不同模块, 校验不同权限
//                    SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
                })
                .setError(e -> {
                    return SaResult.error(e.getMessage());
                });
    }

    /**
     *  actuator 健康检查接口 做账号密码鉴权
     */
    @Bean
    public SaReactorFilter actuatorFilter() {
        String username = SpringUtil.getProperty("spring.cloud.nacos.discovery.metadata.username");
        String password = SpringUtil.getProperty("spring.cloud.nacos.discovery.metadata.userpassword");
        return new SaReactorFilter()
                .addInclude("/actuator", "/actuator/**")
                .setAuth(obj -> {
                    SaHttpBasicUtil.check(username + ":" + password);
                })
                .setError(e -> SaResult.error(e.getMessage()).setCode(HttpStatus.UNAUTHORIZED.value()));
    }
}
